//
//  HomeViewController.swift
//  ShiZhe
//
//  Created by 陈卿伟 on 16/8/23.
//  Copyright © 2016年 陈卿伟. All rights reserved.
//

import UIKit
import SDWebImage
import Alamofire
import SwiftyJSON


//有一个 bug 再进去标签选择页之前 如果选择了某个menu 在所有menu项 在标签选择页面删除光了之后 回到首页 原来那么menu虽然被删除了 但是数据还在 就会显示在热门那里  稍晚解决一下

class HomeViewController: MainViewController {
    
    var segmentView:SegmentView!//顶部选择器
    var tableView:HomeTableView!//tableView
    var cell:HomeTableViewCell!
    var tagSelected = 10000  //记录上一个被点击的item项
    
    var menuName:Array<String> = ["热门","关注","最新"]//已关注的menuname
    var menuID:Array<String> = ["1000","10001","10002"]//已关注的menuid
    
    var questionModel = [QuestionModel]()
    var page:Int = 1
    var loadMoreEnable:Bool = true//是否当前正在加载新数据 防止一直请求加载
    var haveMoreData:Bool = false//判断最后一次加载请求有没有得到数据，如果没有得到数据 说明后面没有数据了
    
    
    //模拟数据  先自定义一下
    var rankArr_ranking = ["234","1132","1","95","22","7","234","1132","1","95","22","7","234","1132","1","95","22","7","234","1132","1","95","22","7","234","1132","1","95","22","7","234","1132","1","95","22","7","234","1132","1","95","22","7","234","1132","1","95","22","7"]
    var preImage = ["http://img2.3lian.com/2014/f4/110/d/46.jpg","http://sc.jb51.net/uploads/allimg/130701/2-130f1155f55p.jpg","http://www.ld12.com/upimg358/allimg/c140921/14112Y103131Z-33133.jpg","http://d.hiphotos.baidu.com/zhidao/pic/item/aec379310a55b3194009f89542a98226cefc1759.jpg","http://img15.3lian.com/2015/h1/42/d/30.jpg","http://pic67.nipic.com/file/20150520/9448607_211842731000_2.jpg","http://img2.3lian.com/2014/f6/153/d/69.jpg","http://img5.imgtn.bdimg.com/it/u=3628972722,3757471413&fm=206&gp=0.jpg","http://img2.3lian.com/2014/f5/33/d/26.jpg","http://img1.3lian.com/img013/v2/78/d/2.jpg","http://b.hiphotos.baidu.com/zhidao/wh%3D450%2C600/sign=b4f7f43ee51190ef01ae9adbfb2bb120/d6ca7bcb0a46f21f8fcb7a80f4246b600d33ae61.jpg","http://img1.3lian.com/2015/w7/63/d/1.jpg","http://img2.3lian.com/2014/f4/110/d/46.jpg","http://sc.jb51.net/uploads/allimg/130701/2-130f1155f55p.jpg","http://www.ld12.com/upimg358/allimg/c140921/14112Y103131Z-33133.jpg","http://d.hiphotos.baidu.com/zhidao/pic/item/aec379310a55b3194009f89542a98226cefc1759.jpg","http://img15.3lian.com/2015/h1/42/d/30.jpg","http://pic67.nipic.com/file/20150520/9448607_211842731000_2.jpg","http://img2.3lian.com/2014/f6/153/d/69.jpg","http://img5.imgtn.bdimg.com/it/u=3628972722,3757471413&fm=206&gp=0.jpg","http://img2.3lian.com/2014/f5/33/d/26.jpg","http://img1.3lian.com/img013/v2/78/d/2.jpg","http://b.hiphotos.baidu.com/zhidao/wh%3D450%2C600/sign=b4f7f43ee51190ef01ae9adbfb2bb120/d6ca7bcb0a46f21f8fcb7a80f4246b600d33ae61.jpg","http://img1.3lian.com/2015/w7/63/d/1.jpg","http://img2.3lian.com/2014/f4/110/d/46.jpg","http://sc.jb51.net/uploads/allimg/130701/2-130f1155f55p.jpg","http://www.ld12.com/upimg358/allimg/c140921/14112Y103131Z-33133.jpg","http://d.hiphotos.baidu.com/zhidao/pic/item/aec379310a55b3194009f89542a98226cefc1759.jpg","http://img15.3lian.com/2015/h1/42/d/30.jpg","http://pic67.nipic.com/file/20150520/9448607_211842731000_2.jpg","http://img2.3lian.com/2014/f6/153/d/69.jpg","http://img5.imgtn.bdimg.com/it/u=3628972722,3757471413&fm=206&gp=0.jpg","http://img2.3lian.com/2014/f5/33/d/26.jpg","http://img1.3lian.com/img013/v2/78/d/2.jpg","http://b.hiphotos.baidu.com/zhidao/wh%3D450%2C600/sign=b4f7f43ee51190ef01ae9adbfb2bb120/d6ca7bcb0a46f21f8fcb7a80f4246b600d33ae61.jpg","http://img1.3lian.com/2015/w7/63/d/1.jpg","http://img2.3lian.com/2014/f4/110/d/46.jpg","http://sc.jb51.net/uploads/allimg/130701/2-130f1155f55p.jpg","http://www.ld12.com/upimg358/allimg/c140921/14112Y103131Z-33133.jpg","http://d.hiphotos.baidu.com/zhidao/pic/item/aec379310a55b3194009f89542a98226cefc1759.jpg","http://img15.3lian.com/2015/h1/42/d/30.jpg","http://pic67.nipic.com/file/20150520/9448607_211842731000_2.jpg","http://img2.3lian.com/2014/f6/153/d/69.jpg","http://img5.imgtn.bdimg.com/it/u=3628972722,3757471413&fm=206&gp=0.jpg","http://img2.3lian.com/2014/f5/33/d/26.jpg","http://img1.3lian.com/img013/v2/78/d/2.jpg","http://b.hiphotos.baidu.com/zhidao/wh%3D450%2C600/sign=b4f7f43ee51190ef01ae9adbfb2bb120/d6ca7bcb0a46f21f8fcb7a80f4246b600d33ae61.jpg","http://img1.3lian.com/2015/w7/63/d/1.jpg"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //title设为图片
        self.navigationItem.titleView = UIImageView(image: UIImage(named: "homeTitleImage"))
        self.addSegmentView()
        self.addTableView()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(true)
        self.navigationItem.leftBarButtonItem?.customView?.hidden = false
        menuName = ["热门","关注","最新"]
        menuID = ["1000","10001","10002"]
        tagSelected = 10000
        self.judgeHaveLogIn()//判断是否登录 没登录就显示登陆界面
    }
}


//MARK:--UI
extension HomeViewController{
    
    //判断是否登录，如果还没登录，就显示登录界面
    func judgeHaveLogIn(){
        if NSUserDefaults.standardUserDefaults().boolForKey(ISLOGIN) == false{
            let logInView = LogInViewControll()
            self.addChildViewController(logInView)
            logInView.didMoveToParentViewController(self)
            logInView.view.frame = MainBounds
            self.view.addSubview(logInView.view)
        }else{
            self.getAlreadyMenuAlamofire()
        }
    }
    
    
    //添加degmentView
    func addSegmentView(){
        segmentView = SegmentView(frame: CGRect(x: 0,y: 0,width: WidthAPP,height: 40))
        self.view.addSubview(segmentView)
        segmentView.itemArr = menuName
        segmentView.createSegmentItem()
        
        //为item添加点击事件
        for i in 0..<self.menuName.count{
            let itemButton = self.view.viewWithTag(10000+i) as! UIButton
            itemButton.addTarget(self, action: #selector(self.segmItemClick(_:)), forControlEvents: .TouchUpInside)
        }
        
        //为更多标签选择按钮添加点击事件
        segmentView.moreButton.addTarget(self, action: #selector(self.moreButtonClick(_:)), forControlEvents: .TouchUpInside)
        
    }
    
    //添加tableView
    func addTableView(){
        tableView = HomeTableView(frame: CGRect(x: 0, y: 40, width: WidthAPP, height: HeightAPP-40-49))
        tableView.delegate = self
        tableView.dataSource = self
        tableView.refresh.addTarget(self, action: #selector(self.refreshEvent(_:)), forControlEvents: .ValueChanged)
        self.view.addSubview(tableView)
    }
    
    
    //对cell的操作
    func operationToCell(cell:HomeTableViewCell,row:Int){
        let model = self.questionModel[row]
        cell.avatarView.sd_setImageWithURL(NSURL(string: "http://\(model.head_image)"))
        cell.userName.text = model.user_name
        cell.rankLabel.text = "\(model.menu_name)榜 No: \(rankArr_ranking[row])"
        cell.informationLabel.text = "阅读 \(model.read_times) . 付款满意率 \(makeFloatToInt(model.pay_satisfy))"
        cell.createQuestionLabel(model.q_name)
        cell.createSubjectIcon(model.menu_name)
//        SDImageCache.sharedImageCache().clearDisk()
        cell.previewImage.setImageForSDWebImage(cell.previewImage, url: NSURL(string: preImage[row]))
    }
    
    
    //将小数转化为百分数
    func makeFloatToInt(floatString:NSString)->String{
        let satisfyFloat = floatString.floatValue
        let satisfyInt = satisfyFloat*100
        return "\(satisfyInt)%"
    }
    
}

//MARK:--点击事件
extension HomeViewController{
    //刷新事件
    func refreshEvent(sender:UIRefreshControl){
        if sender.refreshing == true{
            sender.attributedTitle = NSAttributedString(string: "正在刷新")
            self.questionModel = []
            self.page = 1
            self.getSomeMenuItemAlamofire(self.menuID[tagSelected-10000])
        }
    }

    //segmentItem的点击事件
    func segmItemClick(sender:UIButton){
        let tag = sender.tag
        self.questionModel = []
        self.page = 1
        self.getSomeMenuItemAlamofire(self.menuID[tag-10000])
        if tag != tagSelected{
            let item = self.view.viewWithTag(tagSelected) as! UIButton
            sender.selected = true
            item.selected = false
            tagSelected = tag
            self.moveForRedLine(sender.frame.origin, size: sender.frame.size)
        }
    }
    
    //redline的位移
    func moveForRedLine(point:CGPoint,size:CGSize){
        UIView.animateWithDuration(0.2, delay: 0, options: .CurveEaseOut, animations: {
            self.segmentView.redLine.frame = CGRect(x: point.x, y: 36, width: size.width, height: 2)
            }, completion: nil)
    }
    
    
    //moreButton点击事件
    func moreButtonClick(sender:UIButton){
        self.navigationController?.pushViewController(MoreItemController(), animated: true)
    }

}


//MARK:--tableView   delegate   datasource
extension HomeViewController:UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.questionModel.count
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 121*SCALEH
    }
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headView = HeadView(frame: CGRect(x: 0,y: 0,width: WidthAPP,height: 121*SCALEH))
        return headView
    }
    
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 60
    }
    
    func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footView = FootView(frame: CGRect(x: 0,y: 0,width: WidthAPP,height: 60), loadMoreNow: haveMoreData)
        return footView
    }
    
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        cell = HomeTableViewCell(style: .Default, reuseIdentifier: "HomeCell")
        self.operationToCell(cell, row: indexPath.row)
        self.tableView.rowHeight = cell.rowHeight
        //必须滑到最后 并且 当前没有正在请求 并且 后面还有数据  才会再进行请求
        if indexPath.row == self.questionModel.count-1 && self.loadMoreEnable == true && self.haveMoreData == true{
            page += 1
            self.getSomeMenuItemAlamofire(self.menuID[tagSelected-10000])
        }
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        self.navigationController?.pushViewController(DetailsViewController(), animated: true)
    }
}


//MARK:--Alamofire
extension HomeViewController{
    //得到已经关注的menu
    func getAlreadyMenuAlamofire(){
        let headers = ["token":OperateUserDefaults.takeUserInfo().token]
        Alamofire.request(.POST, "http://srxapp.zhekd.com/ios.php/Menu/get_user_menu", headers: headers).responseJSON { (data) in
            let json = JSON(data: data.data!).arrayValue
            for i in 0..<json.count{
                let menu_id = json[i]["menu_id"].stringValue
                let menu_name = json[i]["menu_name"].stringValue
                self.menuID.insert(menu_id, atIndex:  self.menuID.count)
                self.menuName.insert(menu_name, atIndex:  self.menuName.count)
            }
            dispatch_async(dispatch_get_main_queue(), { 
                self.segmentView.removeFromSuperview()
                self.addSegmentView()
            })
        }
    }
    
    //选择某个menuitem后得到这个menuitem下面的数据
    func getSomeMenuItemAlamofire(menu_id:String){
        print(tagSelected)
        self.loadMoreEnable = false
        self.haveMoreData = true
        let parameters = ["menu_id":menu_id,"page":"\(page)"]
        let headers = ["token":OperateUserDefaults.takeUserInfo().token]
        Alamofire.request(.POST, "http://srxapp.zhekd.com/ios.php/Question", parameters: parameters, encoding: .JSON, headers: headers).responseJSON { (data) in
            let json = JSON(data: data.data!).arrayValue
            let startCount = self.questionModel.count
            //如果json有数据 再去执行添加数据 不然就告诉table 已经没有数据了
            if json.count != 0{
                for i in startCount..<(startCount+json.count){
                    let row = i - startCount
                    let userID = json[row]["user_id"].stringValue
                    let userName = json[row]["user_name"].stringValue
                    let avatar = json[row]["head_image"].stringValue
                    let question = json[row]["q_name"].stringValue
                    let menuName = json[row]["menu_name"].stringValue
                    let menuID = json[row]["menu_id"].stringValue
                    let read_times = json[row]["read_times"].stringValue
                    let pay_satisfy = json[row]["pay_satisfy"].stringValue
                    let questionModel = QuestionModel(user_id: userID, user_name: userName, head_image: avatar, q_name: question, menu_name: menuName, menu_id: menuID, read_times: read_times, pay_satisfy: pay_satisfy)
                    self.questionModel.insert(questionModel, atIndex: i)
                }
            }else{
                self.haveMoreData = false
            }
            
            dispatch_async(dispatch_get_main_queue(), {
                self.loadMoreEnable = true
                self.tableView.reloadData()
                self.tableView.refresh.endRefreshing()
                self.tableView.refresh.attributedTitle = NSAttributedString(string: "继续下拉即可刷新")
            })
        }
    }
}













